import os

from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager
from django.core.mail import send_mail
from django.db import models
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _


class OverwriteFileStorage(FileSystemStorage):
    """文件字段上传时覆盖文件，不自动重命名"""

    # This method is actually defined in Storage
    def get_available_name(self, name, **kwargs):
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name  # simply returns the name passed


def avatar_upload_to(instance, filename):
    return 'avatars/' + str(instance.pk)


class BBSUserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)


class BBSUser(AbstractBaseUser, PermissionsMixin):
    nickname = models.CharField("昵称", max_length=50, blank=False)
    desc = models.TextField("个人简介", blank=True)
    renzheng = models.CharField("认证", max_length=50, blank=True)
    vip = models.SmallIntegerField("VIP等级", default=0)
    coin = models.IntegerField("金币", default=0)
    avatar = models.ImageField("头像", default='assets/images/avatar/default.png', upload_to=avatar_upload_to,
                               storage=OverwriteFileStorage())
    sex = models.CharField("性别", max_length=10, choices=[('male', '男'), ('female', '女')], blank=True)
    city = models.CharField("城市", max_length=200, blank=True)
    date_joined = models.DateTimeField("加入时间", auto_now_add=True)

    email = models.EmailField(_('email address'), blank=False, null=False, unique=True)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )

    objects = BBSUserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['nickname', 'renzheng', 'sex', 'city']

    def clean(self):
        super(BBSUser, self).clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        """
        Returns the first_name plus the last_name, with a space in between.
        """
        return self.nickname.strip()

    def get_short_name(self):
        "Returns the short name for the user."
        return self.nickname.strip()[:10]

    def email_user(self, subject, message, from_email=None, **kwargs):
        """
        Sends an email to this User.
        """
        send_mail(subject, message, from_email, [self.email], **kwargs)

    class Meta:
        verbose_name = "用户"
        verbose_name_plural = "论坛用户"

    @property
    def reply_count(self):
        return self.commentmodel_set.count()

    def __unicode__(self):
        return self.email

    __str__ = __unicode__


class CommentModel(models.Model):
    content = models.TextField("内容", blank=False)
    post = models.ForeignKey("content.PostModel", verbose_name="文章", on_delete=models.DO_NOTHING)
    user = models.ForeignKey(BBSUser, verbose_name="评论用户")
    create_at = models.DateTimeField(auto_now_add=True)
    is_adopted = models.BooleanField("已采纳", default=False)
    likers = models.ManyToManyField(BBSUser, verbose_name="点赞用户", related_name="liker")

    class Meta:
        verbose_name = "评论"
        verbose_name_plural = verbose_name

    @property
    def like_count(self):
        return self.likers.count()

    def __unicode__(self):
        return self.post.title

    __str__ = __unicode__


class SignModel(models.Model):
    user = models.ForeignKey(BBSUser, verbose_name="签到用户")
    sign_date = models.DateField("签到日期", editable=False, auto_now_add=True)
    coin = models.IntegerField("获得金币", default=0)

    class Meta:
        verbose_name = "签到"
        verbose_name_plural = verbose_name
        unique_together = (('user', 'sign_date'),)

    def __unicode__(self):
        return self.user.email + '-' + self.sign_date.strftime('%y%m%d')

    __str__ = __unicode__


class MessageModel(models.Model):
    content = models.TextField("内容", blank=False)
    sender = models.ForeignKey(BBSUser, blank=False, verbose_name="发送者", related_name="message_sender")
    target = models.ForeignKey(BBSUser, blank=False, verbose_name="接收人", related_name="message_target")
    read = models.BooleanField("已读", default=False, editable=False)
    create_at = models.DateTimeField("发送时间", auto_now_add=True)

    class Meta:
        verbose_name = "消息"
        verbose_name_plural = verbose_name
        ordering = ('-create_at',)

    def __unicode__(self):
        return self.content[:50]

    __str__ = __unicode__


@receiver(post_save, sender=SignModel)
def signed_add_coin(instance, **kwargs):
    # 自动添加签到的金币
    instance.user.coin += instance.coin
    instance.user.save()
